package com.meiyou.Interceptor;


import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.meiyou.utils.JsonUtils;
import com.meiyou.utils.Msg;
import com.meiyou.utils.jedis.JedisClient;
import com.meiyou.utils.jedis.JedisClientPool;

public class MyInterceptor implements HandlerInterceptor{

	@Autowired
	JedisClient jedisClient;
	@Autowired
	JedisClientPool jedisClientPool;
	
	public final static String USER_REDIS_SESSION = "user-redis-session";
	
	/***
	 * 请求之前拦截
	 * */

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 
			Object handler)
			throws Exception {
		/**
		   *        返回true，请求ok，放行
		   *        返回false，请求被拦截，返回
		 * */
		String userId = request.getHeader("headerId");
		String userToken = request.getHeader("headerToken");
		if(StringUtils.isNotBlank(userId) && StringUtils.isNotBlank(userToken)) {
			String uniqueToken = jedisClientPool.get(USER_REDIS_SESSION+":"+userId);
			if(StringUtils.isEmpty(uniqueToken) && StringUtils.isBlank(uniqueToken)) {
				System.out.println("登录信息过期，请重新登录。。。。");
				returnErrorResponse(response,Msg.tokenfail().add("file", "登录信息过期，请重新登录"));
				return false;
			}else {
				if(!uniqueToken.equals(userToken)) {
					System.out.println("账号被挤出。。。。");
					returnErrorResponse(response,Msg.tokenfail().add("file", "账号被挤出"));
				}
			}			
		}else {
			System.out.println("请登录。。。。");
			returnErrorResponse(response,Msg.fail().add("file", "请登录"));
			return false;
		}	
		//token没过期，重置token时间
		jedisClientPool.setValueTime(USER_REDIS_SESSION+":"+userId,userToken,1*60*10);
		return true;
	}
	/**
	   * 请求被拦截返回
	 * **/
	public void returnErrorResponse(HttpServletResponse response,Msg result) throws IOException {
		OutputStream out = null;
		try {
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/json");
			out = response.getOutputStream();
			out.write(JsonUtils.objectToJson(result).getBytes("utf-8")); //把result转换成json格式
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(out!=null) {
				out.close();
			}
		}
	}


	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {	
	}


	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}
}